package api

import (
	"gitee.com/gcom/gbox/errors"
	"gitee.com/gcom/stockdock/core/router"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/core/sys"
	"net/http"
)

type createUserForm struct {
	Username string `validate:"gte=5,lte=20"`
	Password string `validate:"gte=8,lte=20"`
	Role     string `validate:"required"`
}

func init() {
	router.PubRouter.HandleFunc("/login", login).Methods("POST")
	router.PubRouter.HandleFunc("/logout", logout).Methods("POST")
	router.AdminRouter.HandleFunc("/user/create", createUser).Methods("POST")
}

func login(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	r.ParseForm()
	username := s.GetUrlVal("username", r.Form)
	password := s.GetUrlVal("password", r.Form)
	if username == "" || password == "" {
		s.ResFail(ctx, 400, "请输入有效的用户名和密码")
		return
	}

	u, err := sys.Login(ctx, username, password)
	if err != nil {
		s.ResFail(ctx, 400, errors.Cause(err).Error())
		return
	}
	var ses = s.GetSession(ctx)
	ses.UserId = u.Id
	ses.Role = u.Role
	s.ResOk(ctx, "登录成功")
}

func logout(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	var ses = s.GetSession(ctx)
	ses.Discard()
	s.ResOk(ctx, "")
}

func createUser(w http.ResponseWriter, r *http.Request) {
	ctx := s.GetTracerCtx(w, r)
	r.ParseForm()
	userForm := createUserForm{}
	if ok := s.ParseAndValid(ctx, r.PostForm, &userForm); !ok {
		return
	}

	_, err := sys.AddUser(ctx, userForm.Username, userForm.Password, userForm.Role)
	if err != nil {
		s.ResError(ctx, 500, err)
		return
	}
	s.ResOk(ctx, "创建成功")
}
